package com.lib.common.utils

import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.os.Build
import android.webkit.WebSettings
import com.lib.common.repository.common.ComSharePreHelper
import com.lib.common.repository.common.SpKeyInComSp
import com.lib.common.repository.datacenter.DataCenter
import com.lib.common.repository.user.UserInfoRepository
import com.lib.framework.manager.ContextManager
import com.lib.framework.manager.RunningActivityManager
import com.lib.framework.module.glide.GlideHlper
import com.lib.framework.utils.AppUtil
import com.lib.framework.utils.FileUtil
import com.lib.framework.utils.NetUtil
import java.util.*
import kotlin.system.exitProcess


/**
 * Copyright (C), 2020-2020, 享物说
 * FileName: Utils
 * Author: keanbin
 * Date: 2020-02-05 17:12
 * Description: 工具类
 * History:
 * <author> <time> <version> <desc>
 * 作者姓名 修改时间 版本号 描述
 */
class ComUtils {

    companion object {

        /**
         * 退出登陆需要调用的函数
         */
        val sLogoutCallList = mutableListOf<()-> Unit>()

        /**
         * 退出登陆页面重置函数
         */
        var sLogoutPageResetCall: (()-> Unit)? = null

        /**
         * 清空 app 的缓存
         */
        fun cleanAppCache() {
            val context = ContextManager.applicationContext
            FileUtil.deleteFilesInDir(FileUtil.getAppRootDir(context))
            FileUtil.deleteFilesInDir(context.cacheDir)
            GlideHlper.clearCache(context)
        }

        /**
         * 重启应用
         */
        fun relaunchApp() {
            // 关闭所有页面
            RunningActivityManager.finishAllActivity()

            val context = ContextManager.applicationContext
            val intent = context.packageManager.getLaunchIntentForPackage(context.packageName)
            val restartIntent = PendingIntent.getActivity(context.applicationContext, 0, intent, PendingIntent.FLAG_ONE_SHOT)
            val mgr = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager?
            if (mgr != null && intent != null) {
                mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 500, restartIntent) // X秒钟后重启应用
            }

            exitProcess(0)
        }

        /**
         * 退出登陆
         */
        fun logout() {
            DataCenter.setIsLogin(false)

            // 退出登陆 app 层需要清空的逻辑函数
            for (function in sLogoutCallList) {
                function()
            }

            DataCenter.setToken("")
            UserInfoRepository.getInstance().clear()

            // 退出登陆页面重置函数
            val logoutPageResetCall = sLogoutPageResetCall ?: return
            logoutPageResetCall()
        }

        /**
         * 获取 User-Agent
         */
        fun getUserAgent(): String {
            var userAgent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                try {
                    WebSettings.getDefaultUserAgent(ContextManager.applicationContext)
                } catch (e: Exception) {
                    System.getProperty("http.agent")
                }

            } else {
                System.getProperty("http.agent")
            }

            if (userAgent.isNullOrEmpty()) {
                userAgent = ""
            }

            val sb = StringBuffer()
            var i = 0
            val length = userAgent.length
            while (i < length) {
                val c = userAgent[i]
                if (c <= '\u001f' || c >= '\u007f') {
                    sb.append(String.format("\\u%04x", c.toInt()))
                } else {
                    sb.append(c)
                }
                i++
            }

            return sb.toString()
        }

        /**
         * 生成指定长度的随机数
         */
        fun getRandomString(length: Int): String {
            //产生随机数
            val random = Random()
            val sb = StringBuffer()
            //循环length次
            for (i in 0 until length) {
                //产生0-2个随机数，既与a-z，A-Z，0-9三种可能
                val number = random.nextInt(3)
                var result: Long = 0
                when (number) {
                    //如果number产生的是数字0；
                    0 -> {
                        //产生A-Z的ASCII码
                        result = Math.round(Math.random() * 25 + 65)
                        //将ASCII码转换成字符
                        sb.append(result.toChar().toString())
                    }
                    1 -> {
                        //产生a-z的ASCII码
                        result = Math.round(Math.random() * 25 + 97)
                        sb.append(result.toChar().toString())
                    }
                    2 ->
                        //产生0-9的数字
                        sb.append(Random().nextInt(10).toString())
                }
            }
            return sb.toString()
        }

        /**
         * 获取设备id
         */
        fun getDeviceId(): String {
            var deviceId = ComSharePreHelper.getString(SpKeyInComSp.SP_KEY_DEVICE_ID, "")
            if (deviceId.isNotEmpty()) {
                return deviceId
            }

            /**
             * from mac address
             */
            deviceId = getMacAddressString()
            if (deviceId.isNotEmpty()) {
                ComSharePreHelper.putString(SpKeyInComSp.SP_KEY_DEVICE_ID, deviceId)
                return deviceId
            }

            /**
             * from android id
             */
            deviceId = AppUtil.getAndroidID(ContextManager.applicationContext) ?: ""
            if (deviceId.isNotEmpty()) {
                ComSharePreHelper.putString(SpKeyInComSp.SP_KEY_DEVICE_ID, deviceId)
                return deviceId
            }

            /**
             * from uuid random
             */
            deviceId = getDeviceIdFromUUID()
            if (deviceId.isNotEmpty()) {
                ComSharePreHelper.putString(SpKeyInComSp.SP_KEY_DEVICE_ID, deviceId)
                return deviceId
            }

            return deviceId
        }

        /**
         * MAC地址
         *
         * @return
         */
        private fun getMacAddressString(): String {
            return NetUtil.getMacAddress()?.replace(":", "") ?: ""
        }

        /**
         * 生成 uuid
         */
        private fun getDeviceIdFromUUID(): String {
            return UUID.randomUUID().toString().replace("-", "")
        }
    }
}